<template>
  <!-- Two-way Data-Binding -->
  <div class="news-container">
    <div class="news-content">
      <div class="news-write" v-loading="loading">
        <div class="write-from">
          <el-form
            :model="ruleForm"
            :rules="rules"
            label-position="top"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="输入公告标题" prop="title">
              <el-input class="input-write" v-model="ruleForm.title"></el-input>
            </el-form-item>
            <el-form-item label="选择上传图片">
              <div class="write-img">
                <el-upload
                  class="upload-demo"
                  name="file"
                  :action="action"
                  ref="upload"
                  :auto-upload="false"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                  :multiple="true"
                  list-type="picture"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过4M
                  </div>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item label="编辑新闻内容" prop="text">
              <div class="write-text">
                <quill-editor
                  ref="myQuillEditor"
                  v-model="ruleForm.text"
                  @change="alertValue($event)"
                  :options="editorOption"
                />
                <div class="write-text-num">{{ textLength }}/800</div>
              </div>
            </el-form-item>
            <div class="write-text-tt" v-show="IsWriteText">
              请最少输入十个字符
            </div>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >立即发布</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="write-img"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { request, baseUrl } from "@/network/request.js";
export default {
  name: "notice",
  data() {
    return {
      action: baseUrl + "/add",
      content: "", //默认显示的标题，可以附带默认样式
      IsWriteText: false,
      editorOption: {
        placeholder: "输入公告内容...",
        modules: {
          toolbar: [
            [{ color: [] }, { background: [] }], // 颜色选择
            [{ align: [] }], // 居中
          ],
        },
      },
      ruleForm: {
        title: "",
        text: "",
      },
      textLength: 0,
      rules: {
        title: [
          { required: true, message: "请输入公告标题", trigger: "blur" },
          { min: 5, max: 40, message: "长度在 5到 40 个字符", trigger: "blur" },
        ],
      },
      loading: false,
      IsFile: false,
      imgNum: 0,
    };
  },
  components: {
    quillEditor,
  },
  methods: {
    // 图片上传限制
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 4; //文件大小4m
      console.log(file.uid);
      if (file.uid) {
        // this.Isimg = false;
        this.IsFile = true; //有图片
      } else {
        this.IsFile = false;
      }
      if (!isJPG) {
        this.$message.error("上传图片是 JPG,png格式!");
        this.loading = false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 4MB!");
        this.loading = false;
      }
      return isJPG && isLt2M;
    },
    //上传图片成功，成功后发送表单
    handleAvatarSuccess(res, file, fileList) {
      this.imgNum += 1;
      let itemImg = [];
      console.log(fileList);
      for (const i in fileList) {
        console.log(i);
        if (fileList[i].response.imgName.length > 0) {
          itemImg.push(...fileList[i].response.imgName);
        }
      }
      if (this.imgNum == fileList.length) {
        // this.ruleForm.text = this.ruleForm.text.replace(
        //   /<p>/gi,
        //   '<p style="font-size: 35rpx; line-height: 1.67;padding: 15rpx 0;">'
        // );
        this.ruleForm.text = this.ruleForm.text.replace(
          /<p>/gi,
          '<p style="line-height: 1.67; margin-bottom: 0.5rem !important;">'
        );
        request({
          method: "post",
          url: "/add_notice",
          data: {
            title: this.ruleForm.title,
            img: itemImg,
            text: this.ruleForm.text,
          },
        })
          .then((res) => {
            this.loading = false;
            console.log(res);
            this.navTo("/home/notice-info/notice-list");
          })
          .catch((err) => {
            console.log(err);
          });
      } else if (res.mesg == "off") {
        return;
      } else {
        this.$message.error("上传失败");
      }
    },

    //提交表单
    submitForm(formName) {
      //数据检验

      if (this.ruleForm.title.length < 5 || this.ruleForm.title.length > 40) {
        // this.IsWriteText = true;
        return false;
      }
      if (this.textLength < 10) {
        this.IsWriteText = true;
        return false;
      }
      this.loading = true;

      setTimeout(() => {
        this.$refs.upload.submit(); //上传图片，执行beforeAvatarUpload，得出是否有图片
        // 若果没有图片，直接发送表单
        console.log(this.IsFile);
        if (!this.IsFile) {
          // console.log(this.Isimg);
          // this.loading = false;
          this.ruleForm.text = this.ruleForm.text.replace(
            /<p>/gi,
            '<p style="line-height: 1.67; margin-bottom: 0.5rem !important;">'
          );
          request({
            method: "post",
            url: "/add_notice",
            data: {
              title: this.ruleForm.title,
              img: "无",
              text: this.ruleForm.text,
            },
          })
            .then((res) => {
              // console.log(res);
              this.loading = false;
              this.navTo("/home/notice-info/notice-list");
            })
            .catch((err) => {
              console.log(err);
            });
        }
      }, 500);
    },
    //移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    //预览
    handlePreview(file) {
      console.log(file + "11");
    },
    // 文章内容限制
    alertValue(e) {
      e.quill.deleteText(800, 1); //设置文字数量限制
      console.log(e.quill.getLength() - 1);
      this.textLength = e.quill.getLength() - 1;
      this.IsWriteText = false;
    },
    navTo(routerUrl) {
      // console.log(routerUrl);

      this.$router.push({
        path: routerUrl,
        query: {
          // // category: getCategoryName(this.data.category),
          // categoryText: '畅销精选'
        },
      });
    },
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
  },
  mounted() {
    console.log("this is current quill instance object", this.editor);
  },
};
</script>

<style lang="scss">
@import "@/assets/styles/global.scss";
.news-container {
  padding: 20px;
  .news-content {
    .news-write {
      .write-from {
        width: 100%;
        // height: 100vh;
        background-color: #fff;
        padding: 20px;
        box-sizing: border-box;
        .input-write {
          width: 50%;
        }
        .quill-editor {
          height: 200px;
          width: 80%;
        }
        .write-text-num {
          position: absolute;
          right: 21%;
          bottom: 0px;
        }
        .write-text-tt {
          color: #f56c6c;
          font-size: 12px;
          line-height: 1;
          padding-bottom: 4px;
        }
      }

      // .write-img {
      //   // border: 1px solid #ccc;
      // }
      .write-text {
        // border: 1px solid #ccc;
        height: 250px;
      }
    }
  }
}
</style>
